<?php

namespace app\rental\controller;

use app\admin\model\RouteModel;
use cmf\controller\AdminBaseController;
use app\rental\model\RentalCategoryModel;
use think\Db;
use app\admin\model\ThemeModel;


class AdminCategoryController extends AdminBaseController
{
    /**
     * 汽车分类列表
     * @adminMenu(
     *     'name'   => '分类管理',
     *     'parent' => 'rental/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 2,
     *     'icon'   => '',
     *     'remark' => '汽车分类列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $rentalCategoryModel = new RentalCategoryModel();
        $category       = $rentalCategoryModel->order('list_order desc')->paginate();
        $this->assign('category', $category);
        $this->assign('page', $category->render());
        return $this->fetch();
    }

    /**
     * 添加汽车分类
     * @adminMenu(
     *     'name'   => '添加汽车分类',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '添加汽车分类',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $themeModel        = new ThemeModel();
        $listThemeFiles    = $themeModel->getActionThemeFiles('rental/List/index');
        $carThemeFiles = $themeModel->getActionThemeFiles('rental/Car/index');
        $this->assign('list_theme_files', $listThemeFiles);
        $this->assign('car_theme_files', $carThemeFiles);
        return $this->fetch();
    }

    /**
     * 添加汽车分类提交
     * @adminMenu(
     *     'name'   => '添加汽车分类提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '添加汽车分类提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        $rentalCategoryModel = new RentalCategoryModel();

        $data = $this->request->param();
        if (!empty($data['more']['thumbnail'])) {
                $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
            }
        if(empty(trim($data['name']))){
            $this->error('分类名不能为空');
        }

        if(!empty($rentalCategoryModel->where('name',trim($data['name']))->find())){
            $this->error('该分类已经存在');
        }
        $alias = strtolower(trim($data['alias']));
        $allen = preg_match("/^[a-zA-Z\s]+$/", $alias);
       if(!$allen){
        $this->error('分类别名不支持中文');
       }
       $result =  $rentalCategoryModel->isUpdate(false)->allowField(true)->save($data);
        if ($result == false) {
          $this->error($rentalCategoryModel->getError());
        }
        //设置别名
        $routeModel = new RouteModel();
        $id =  $rentalCategoryModel->id;
        if (!empty($alias) && !empty($id)) {
            $routeModel->setRoute($alias, 'rental/List/index', ['id' => $id], 2, 5000);
            $routeModel->setRoute($alias . '/:id', 'rental/Car/index', ['cid' => $id], 2, 4999);
        }
        $routeModel->getRoutes(true);
        $this->success(lang("SAVE_SUCCESS"),url('AdminCategory/index'));
    }

    /**
     * 编辑汽车分类
     * @adminMenu(
     *     'name'   => '编辑汽车分类',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '编辑汽车分类',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id > 0) {
            $category = RentalCategoryModel::get($id);
            $category['alias'] = $category->alias;
            $themeModel        = new ThemeModel();
            $listThemeFiles    = $themeModel->getActionThemeFiles('rental/List/index');
            $carThemeFiles = $themeModel->getActionThemeFiles('rental/Car/index');
            $this->assign('list_theme_files', $listThemeFiles);
            $this->assign('car_theme_files', $carThemeFiles);
            $this->assign($category->toArray());
            return $this->fetch();
        } else {
            $this->error('操作错误!');
        }

    }

    /**
     * 编辑汽车分类提交
     * @adminMenu(
     *     'name'   => '编辑汽车分类提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '编辑汽车分类提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        $data = $this->request->param();
        $rentalCategoryModel = new RentalCategoryModel();
        if (!empty($data['more']['thumbnail'])) {
                $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
        }
        if(empty(trim($data['name']))){
            $this->error('分类名不能为空');
        }
        $map['id']  = array('neq',$data['id']);
        $map['name'] = trim($data['name']);
        if(!empty($rentalCategoryModel->where($map)->find())){
            $this->error('该分类已经存在');
        }
       $alias = strtolower(trim($data['alias']));
        $allen = preg_match("/^[a-zA-Z\s]+$/", $alias);
       if(!$allen){
        $this->error('分类别名不支持中文');
       }
        if (empty($data['id'])) {
            $this->error('操作错误');
        }
       $result = $rentalCategoryModel->isUpdate(true)->allowField(true)->save($data, ["id" => $data['id']]);

        //设置别名
        $routeModel = new RouteModel();
        if (!empty($data['alias']) && !empty( $data['id'])) {
            $routeModel->setRoute($alias, 'rental/List/index', ['id' => $data['id']], 2, 5000);
            $routeModel->setRoute($alias . '/:id', 'rental/Car/index', ['cid' =>  $data['id']], 2, 4999);
        }
        $routeModel->getRoutes(true);
        $this->success(lang("SAVE_SUCCESS"), url('AdminCategory/index'));
    }



    /**
     * 汽车分类排序
     * @adminMenu(
     *     'name'   => '汽车分类排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '汽车分类排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders(Db::name('rental_category'));
        $this->success("排序更新成功！", '');
    }

    /**
     * 删除汽车分类
     * @adminMenu(
     *     'name'   => '删除汽车分类',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '删除汽车分类',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $rentalCategoryModel = new RentalCategoryModel();
        $id                  = $this->request->param('id');
        //获取删除的内容
        $findCategory = $rentalCategoryModel->where('id', $id)->find();

        if (empty($findCategory)) {
            $this->error('分类不存在!');
        }

        $categoryPostCount = Db::name('rental_category_post')->where('category_id', $id)->count();

        if ($categoryPostCount > 0) {
            $this->error('此分类有内容无法删除!');
        }

        $data   = [
            'object_id'   => $findCategory['id'],
            'create_time' => time(),
            'table_name'  => 'rental_category',
            'name'        => $findCategory['name']
        ];
        $result = $rentalCategoryModel
            ->where('id', $id)
            ->update(['delete_time' => time()]);
        if ($result) {
            Db::name('recycleBin')->insert($data);
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }
}
